package fans_group

import (
	"encoding/json"
	"github.com/spf13/cast"
	"longmen/server/internal/rpc/tencentim/imsdk"
	messages2 "longmen/server/internal/rpc/tencentim/messages"
	"longmen/server/internal/rpc/tencentim/utils"
	"longmen/server/pkg/db/redis/cache"
	pb "longmen/server/pkg/protobuf"
)

func (f *fansGroup) afterMessageProcess() (*pb.CallbackResp, error) {

	allMsg := f.req.GetMsgBody()
	for _, msg := range allMsg {
		switch msg.MsgType {
		case imsdk.TIM_MSG_TYPE_CUSTOM:
			data := msg.MsgContent.Data
			rawBytes := []byte(data)
			comeMsg := messages2.ReplyMessage{}
			err := json.Unmarshal(rawBytes, &comeMsg)
			if err != nil {
				return utils.FailCodeResp(imsdk.TIM_ERROR_CODE_REJECT, "回调消息错误"), nil
			}
			switch comeMsg.Type {
			case messages2.SayReplyMessageType:
				userId := cast.ToString(f.user.UserId)

				//用户消息计数+1 群消息计数+1
				cache.IncrGroupMsgUserNum(userId, f.req.GroupId)
				//清空当前用户未读消息计数
				cache.ResetGroupMsgUserRead(userId, f.req.GroupId)

				if !f.writeChatHistory(rawBytes) {
					return utils.FailCodeResp(imsdk.TIM_ERROR_ERROR, "消息丢失"), nil
				}
			}
		}

	}
	return utils.CallbackOkResp("Ok"), nil

}
